'''
工具模块
'''
import json
from selenium import webdriver
from selenium.webdriver import ChromeOptions
chrome_options = ChromeOptions()
# 失败的两个解决方案
# chrome_options.add_argument('--enable-automation')
# chrome_options.add_experimental_option(
#     'excludeSwitches', ['enable-automation'])
browser = webdriver.Chrome(options=chrome_options)
browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => undefined
    })
  """
})  # 在开启浏览器之前执行脚本去除selenium特征避免被发现是爬虫


def getCookies(websiteName):
    '''
    获取cookies，会打开一个浏览器，然后手动登录，会获取登录后的cookies写入cookies.json中
    @return 是否成功
    '''
    website_map = {
        'zhaopin': "https://sou.zhaopin.com/?jl=543"
    }
    website_url = website_map.get(websiteName)
    if website_url == None:
        return False
    browser.get(website_url)
    input('请随便输入点什么代表你已经登录完成：')
    dictCookies = browser.get_cookies()
    jsonCookies = json.dumps(dictCookies, sort_keys=True, indent=2)
    print(jsonCookies)
    with open(websiteName+'.json', 'w') as f:
        f.write(jsonCookies)
        print('获取成功')
        return True


if __name__ == "__main__":
    getCookies('zhaopin')
